#include "widget.h"
#include "ui_widget.h"

#include <QMouseEvent>
#include <QDebug>
#include <QNetworkAccessManager>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QPainter>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFixedSize(522,994);
    setWindowFlag(Qt::FramelessWindowHint);//边框隐藏


    menuQuit = new QMenu(this);
    //由QNetworkAccessManager发起get请求
    mananger = new QNetworkAccessManager(this);
    //设置菜单项文字颜色
    menuQuit->setStyleSheet("QMenu::item{color:white}");
    QAction *closeAct = new QAction(QIcon(":/res/close.png"), tr("退出"), this);
    menuQuit->addAction(closeAct);
    connect(menuQuit,&QMenu::triggered,this,[=](){// 关闭界面
        this->close();
    });
    connect(mananger,&QNetworkAccessManager::finished,[](){
        qDebug() << "finish!";
    });
    //QUrl urlItBoy("http://t.weather.itboy.net/api/weather/city/101010100");
    //strUrl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v63&appid=87178381&appsecret=C15O5NdL";
    strUrl = "http://gfeljm.tianqiapi.com/api?unescape=1&version=v9&appid=87178381&appsecret=C15O5NdL";
    QUrl urlTianQi(strUrl);
    //指定Url的地址
    QNetworkRequest res(urlTianQi);
    reply = mananger->get(res);
    //网络请求后进行信号读取
    connect(mananger,&QNetworkAccessManager::finished,this,&Widget::readHttpReply);

    mWeekList << ui->labeday0<<ui->labeday1<<ui->labeday2<<ui->labeday3<<ui->labeday4<<ui->labeday5;
    mDateList << ui->labelDayDate1 << ui->labelDayDate2 << ui->labelDayDate3 << ui->labelDayDate4 <<
                  ui->labelDayDate5 << ui->labelDayDate6;
    mIconList << ui->labelWeatherIcon0<< ui->labelWeatherIcon1<< ui->labelWeatherIcon2<< ui->labelWeatherIcon3
                 << ui->labelWeatherIcon4<< ui->labelWeatherIcon5;
    mWeaTypeList << ui->labelWeatherType0<< ui->labelWeatherType1<< ui->labelWeatherType2<< ui->labelWeatherType3
                    << ui->labelWeatherType4<< ui->labelWeatherType5;
    mAirqList << ui->labelAirq1<< ui->labelAirq2<< ui->labelAirq3<< ui->labelAirq4<< ui->labelAirq5<< ui->labelAirq6;

    mFxList <<ui->labelFx0<<ui->labelFx1<<ui->labelFx2<<ui->labelFx3<<ui->labelFx4<<ui->labelFx5;

    mFlList << ui->labelFl0<< ui->labelFl1<< ui->labelFl2<< ui->labelFl3<< ui->labelFl4<< ui->labelFl5;

    //根据keys,设置icon的路径
    mTypeMap.insert("暴雪",":/res/type/BaoXue.png");
    mTypeMap.insert("暴雨",":/res/type/BaoYu.png");
    mTypeMap.insert("暴雨到大暴雨",":/res/type/BaoYuDaoDaBaoYu.png");
    mTypeMap.insert("大暴雨",":/res/type/DaBaoYu.png");
    mTypeMap.insert("大暴雨到特大暴雨",":/res/type/DaBaoYuDaoTeDaBaoYu.png");
    mTypeMap.insert("大到暴雪",":/res/type/DaDaoBaoXue.png");
    mTypeMap.insert("大雪",":/res/type/DaXue.png");
    mTypeMap.insert("大雨",":/res/type/DaYu.png");
    mTypeMap.insert("冻雨",":/res/type/DongYu.png");
    mTypeMap.insert("多云",":/res/type/DuoYun.png");
    mTypeMap.insert("浮沉",":/res/type/FuChen.png");
    mTypeMap.insert("雷阵雨",":/res/type/LeiZhenYu.png");
    mTypeMap.insert("雷阵雨伴有冰雹",":/res/type/LeiZhenYuBanYouBingBao.png");
    mTypeMap.insert("霾",":/res/type/Mai.png");
    mTypeMap.insert("强沙尘暴",":/res/type/QiangShaChenBao.png");
    mTypeMap.insert("晴",":/res/type/Qing.png");
    mTypeMap.insert("沙尘暴",":/res/type/ShaChenBao.png");
    mTypeMap.insert("特大暴雨",":/res/type/TeDaBaoYu.png");
    mTypeMap.insert("undefined",":/res/type/undefined.png");
    mTypeMap.insert("雾",":/res/type/Wu.png");
    mTypeMap.insert("小到中雪",":/res/type/XiaoDaoZhongXue.png");
    mTypeMap.insert("小到中雨",":/res/type/XiaoDaoZhongYu.png");
    mTypeMap.insert("小雪",":/res/type/XiaoXue.png");
    mTypeMap.insert("小雨",":/res/type/XiaoYu.png");
    mTypeMap.insert("雪",":/res/type/Xue.png");
    mTypeMap.insert("扬沙",":/res/type/YangSha.png");
    mTypeMap.insert("阴",":/res/type/Yin.png");
    mTypeMap.insert("雨",":/res/type/Yu.png");
    mTypeMap.insert("雨夹雪",":/res/type/YuJiaXue.png");
    mTypeMap.insert("阵雪",":/res/type/ZhenXue.png");
    mTypeMap.insert("阵雨",":/res/type/ZhenYu.png");
    mTypeMap.insert("中到大雪",":/res/type/ZhongDaoDaXue.png");
    mTypeMap.insert("中到大雨",":/res/type/ZhongDaoDaYu.png");
    mTypeMap.insert("中雪",":/res/type/ZhongXue.png");
    mTypeMap.insert("中雨",":/res/type/ZhongYu.png");

    ui->widget0404->installEventFilter(this);
    ui->widget0405->installEventFilter(this);
}


Widget::~Widget()
{
    delete ui;
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button()==Qt::RightButton){
        menuQuit->exec(QCursor::pos());

    }

    //鼠标当前位置event->globalPos()，窗口当前位置this->pos()，窗口新位置this->move(event->globalPos() - moffSet);
    if(event->button() == Qt::LeftButton){
       moffSet =  event->globalPos() - this->pos();
    }
}

//鼠标左键按下窗口移动到新位置
void Widget::mouseMoveEvent(QMouseEvent *event)
{
    this->move(event->globalPos() - moffSet);
}

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget0404 && event->type() == QEvent::Paint){
        drawTemLineHigh();
        return true;
    }
    if(watched==ui->widget0405 && event->type() == QEvent::Paint){
        drawTemLineLow();
        return true;
    }
    return QWidget::eventFilter(watched,event);
}


void Widget::parseWeatherJsonDataNew(QByteArray rawData)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(rawData);
    if(!jsonDoc.isNull() && jsonDoc.isObject()){
        QJsonObject jsonRoot = jsonDoc.object();
        day[0].mCity = jsonRoot["city"].toString();
        day[0].mPm25 = jsonRoot["aqi"].toObject()["pm25"].toString();
        if(jsonRoot.contains("data") && jsonRoot["data"].isArray()){
            QJsonArray weaArray = jsonRoot["data"].toArray();
            for(int i = 0; i < weaArray.size(); i++){
                QJsonObject obj = weaArray[i].toObject();
                //qDebug() << obj["date"].toString() << obj["wea"].toString();
                day[i].mDate = obj["date"].toString();
                day[i].mWeek = obj["week"].toString();
                day[i].mWeaType = obj["wea"].toString();
                day[i].mTemp = obj["tem"].toString();
                day[i].mTempLow = obj["tem2"].toString();
                day[i].mTempHigh = obj["tem1"].toString();
                day[i].mFx = obj["win"].toArray()[0].toString();
                day[i].mFl = obj["win_speed"].toString();
                day[i].mAirq = obj["air_level"].toString();
                day[i].mTips = obj["air_tips"].toString();
                day[i].mHu = obj["humidity"].toString();

            }
        }
    }
    upDataUi();
}

void Widget::upDataUi()
{
    QPixmap pixmap;
    //解析日期
    ui->labelCurrentDate->setText(day[0].mDate + " " + day[0].mWeek);
    //解析城市名称
    ui->labelCity->setText(day[0].mCity+"市");
    //解析当前温度
    ui->Tmp->setText(day[0].mTemp+"℃");
    ui->labelTempRange->setText(day[0].mTempLow+"℃" + "～" + day[0].mTempHigh+"℃");
    //解析天气类型
    ui->labelWeatherType->setText(day[0].mWeaType);
    ui->labelWeatherCon->setPixmap(mTypeMap[day[0].mWeaType]);
    //感冒指数
    ui->labelGanMao->setText(day[0].mTips);
    //风向
    ui->labelFxType->setText(day[0].mFx);
    //风力
    ui->labelFxType_2->setText(day[0].mFl);
    //PM2.5
    ui->labelPM25Data->setText(day[0].mPm25);
    //湿度
    ui->labelSdData->setText(day[0].mHu);
    //空气质量
    ui->labelAirData->setText(day[0].mAirq);

    ui->labelWeatherType0->setText(day[0].mWeaType);

    for(int i = 0; i < 6; i++){
        QStringList dayList = day[i].mDate.split("-");
        mDateList[i]->setText(dayList.at(1)+"-"+dayList.at(2));
        mWeekList[i]->setText(day[i].mWeek);
        mWeekList[0]->setText("今天");
        mWeekList[1]->setText("明天");
        mWeekList[2]->setText("后天");

        //缩放图片大小和Label大小匹配
        int index = day[i].mWeaType.indexOf("转");
        if(index != -1){
            pixmap = mTypeMap[day[i].mWeaType.left(index)];
        }else{
            pixmap = mTypeMap[day[i].mWeaType];
        }
        pixmap = pixmap.scaled(mIconList[i]->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation);
        mIconList[i]->setMaximumHeight(50);
        mIconList[i]->setMaximumWidth(ui->widget02->width()/6.5);
        mIconList[i]->setPixmap(pixmap);
        mWeaTypeList[i]->setText(day[i].mWeaType);

        QString airQ = day[i].mAirq;
        mAirqList[i]->setText(airQ);
        if(airQ == "优"){
            mAirqList[i]->setStyleSheet("background-color: rgb(150,213,32);border-radius:10px;color: rgb(255, 255, 255);");
        }
        if(airQ == "良"){
            mAirqList[i]->setStyleSheet("background-color: rgb(190,213,32);border-radius:10px;color: rgb(255, 255, 255);");
        }
        if(airQ == "轻度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(255,199,199);border-radius:10px;color: rgb(255, 255, 255);");
        }
        if(airQ == "中度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(255,17,17);border-radius:10px;color: rgb(255, 255, 255);");
        }
        if(airQ == "重度"){
            mAirqList[i]->setStyleSheet("background-color: rgb(153,0,0);border-radius:10px;color: rgb(255, 255, 255);");
        }

        mFxList[i]->setText(day[i].mFx);
        index = day[i].mFx.indexOf("转");
        if(index == -1){
            mFxList[i]->setText(day[i].mFx.left(index));
        }else mFxList[i]->setText(day[i].mFx);
        index = day[i].mFl.indexOf("转");
        if(index == -1){
            mFlList[i]->setText(day[i].mFl.left(index));
        }else mFlList[i]->setText(day[i].mFl);

    }
    update();
}

void Widget::drawTemLineHigh()
{
    QPainter painter(ui->widget0404);
    painter.setBrush(Qt::yellow);
    painter.setPen(Qt::yellow);
    painter.setRenderHint(QPainter::Antialiasing);

    int ave;
    int sum=0;
    int offSet = 0;
    int middle = ui->widget0404->height()/2;
    for(int i = 0; i < 6; i++){
        sum += day[i].mTempHigh.toInt();
    }
    ave = sum/6;
    //定义出6个点
    QPoint point[6];
    for(int i = 0; i < 6; i++){
        point[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = day[i].mTempHigh.toInt() - ave;
        point[i].setY(middle - offSet);
        //画出六个点
        painter.drawEllipse(QPoint(point[i]),4,4);
        //画出当天温度
        painter.drawText(point[i].x()-15,point[i].y()-15,day[i].mTempHigh+"℃");
    }
    //画出六条线
    for(int i = 0; i < 5; i++){
        painter.drawLine(point[i],point[i+1]);
    }

    //painter.drawLine(QPoint(10,10),QPoint(30,30));
}

void Widget::drawTemLineLow()
{
    QPainter painter(ui->widget0405);
    painter.setBrush(Qt::blue);
    painter.setPen(Qt::blue);
    painter.setRenderHint(QPainter::Antialiasing);

    int ave;
    int sum=0;
    int offSet = 0;
    int middle = ui->widget0405->height()/2;
    for(int i = 0; i < 6; i++){
        sum += day[i].mTempLow.toInt();
    }
    ave = sum/6;
    //定义出6个点
    QPoint point[6];
    for(int i = 0; i < 6; i++){
        point[i].setX(mAirqList[i]->x() + mAirqList[i]->width()/2);
        offSet = day[i].mTempLow.toInt() - ave;
        point[i].setY(middle - offSet);
        //画出六个点
        painter.drawEllipse(QPoint(point[i]),4,4);
        //画出当天温度
        painter.drawText(point[i].x()-15,point[i].y()-15,day[i].mTempLow+"℃");
    }
    //画出六条线
    for(int i = 0; i < 5; i++){
        painter.drawLine(point[i],point[i+1]);
    }
}

void Widget::readHttpReply(QNetworkReply* reply)
{
    int resCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
    //大多数服务器返回的字符编码格式是UTF-8
    if(reply->error() == QNetworkReply::NoError && resCode==200){
        QByteArray data = reply->readAll();
        parseWeatherJsonDataNew(data);
        //qDebug() << QString::fromUtf8(data);
    }else{
        //QMessageBox::warning(this,"错误","网络请求失败",QMessageBox::Ok);
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("网络请求失败！");
        mes.setStyleSheet("QPushButton{color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }

}



void Widget::on_btnSreach_clicked()
{
    QString cityNameFromUser = ui->lineEditCity->text();
    QString cityCode = cityCodeUtils.getCityCodeFromName(cityNameFromUser);
    if(cityCode != NULL){
        strUrl += "&cityid=" + cityCode;
        mananger->get(QNetworkRequest(QUrl(strUrl)));
    }else{
        QMessageBox mes;
        mes.setWindowTitle("错误");
        mes.setText("请输入正确的城市名称");
        mes.setStyleSheet("QPushButton{color:red}");
        mes.setStandardButtons(QMessageBox::Ok);
        mes.exec();
    }
}

void Widget::on_lineEditCity_returnPressed()
{
    on_btnSreach_clicked();
}
